package com.hnd.springframerwork.beans.factory.support;

import com.hnd.springframerwork.beans.BeansException;
import com.hnd.springframerwork.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, Constructor ctor, Object... args) {
        Class beanClazz = beanDefinition.getBeanClazz();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanClazz);
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });

        try {
            if (ctor == null) {
                return enhancer.create();
            }
            return enhancer.create(ctor.getParameterTypes(), args);
        } catch (RuntimeException e) {
            throw new BeansException("创建实例失败", e);
        }

    }

}

